package xml1;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

public class Dom4JTest1 {
    public static void main(String[] args) throws Exception {
        // 创建一个Dom4J框架提供的解析器对象
        SAXReader saxReader = new SAXReader();

        // 使用saxReader对象把需要解析的XML文件读成一个Document对象
        Document document =
                saxReader.read("src\\hello_world.xml");

        // 从文档对象中解析XML的全部数据
        Element root = document.getRootElement();
        System.out.println(root.getName());

        // 获取当前全部一级子元素
        List<Element> elements = root.elements("user");
        for (Element element : elements) {
            System.out.println(element.getName());
        }

        // 获取当前元素下某个元素
        Element people = root.element("people");
        System.out.println(people.getText());

        // 如果下面子元素很多user，默认获取第一个
        List<Element> users = root.elements("user");
        Element user = users.get(0);
        System.out.println(user.elementText("name"));


        // 获取元素的属性信息
        System.out.println(user.attributeValue("id"));
        Attribute id = user.attribute("id");
        System.out.println(id.getName());
        System.out.println(id.getValue());

        List<Attribute> attributes = user.attributes();
        for (Attribute attribute : attributes) {
            System.out.println(attribute.getName() + "=" + attribute.getValue());

            // 获取全部的文本内容  获取当前元素下的子元素
            System.out.println(user.elementText("name"));
            System.out.println(user.elementText("地址"));
            System.out.println(user.elementText("password"));

            Element data = user.element("data");
            System.out.println(data.getText());
            System.out.println(data.getTextTrim());// 去除空格
        }
        Element user1 = users.get(1);
        System.out.println(user1.elementText("name"));
    }
}
